package com.jh.user.repository;

import com.jh.user.pojo.UserAccount;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import javax.persistence.LockModeType;
import java.math.BigDecimal;
import java.util.List;
import java.util.Set;


@Repository
public interface UserAccountRepository extends JpaRepository<UserAccount,String>,JpaSpecificationExecutor<UserAccount>{

	@Lock(value = LockModeType.PESSIMISTIC_WRITE)
	@Query("select account from  UserAccount account where account.userId=:userid")
	UserAccount findUserAccountByUseridLock(@Param("userid") long userid);

	@Query("select account from  UserAccount account where account.userId=:userid")
	UserAccount findUserAccountByUserid(@Param("userid") long userid);

	//根据userid删除用户余额记录
	@Modifying
	@Query("delete from UserAccount account where account.userId=:userid")
	void delUserAccount(@Param("userid") long userid);

	@Query("select account from UserAccount account where account.userId = :userId")
	UserAccount getUserAccount(@Param("userId") long userId);

	@Modifying
	@Query("update UserAccount u set u.balance = :subtractBalance, u.freezeBalance = :addFreezeBalance where u.userId = :userId")
	void updateAccount(@Param("userId") long userId, @Param("subtractBalance") BigDecimal subtractBalance, @Param("addFreezeBalance") BigDecimal addFreezeBalance);

	@Lock(value = LockModeType.OPTIMISTIC)
	List<UserAccount> findAllByUserIdIn(Set<Long> userIds, Sort sort);

	@Modifying
	@Query("update UserAccount u set u.rebateBalance = :newRebateBalance, u.freezerebateBalance = :newFreezerebateBalance, u.balance = :newBalance where u.userId = :userId")
	int updateRebateBalance(@Param("userId") long userId, @Param("newRebateBalance") BigDecimal newRebateBalance,
							@Param("newFreezerebateBalance") BigDecimal newFreezerebateBalance, @Param("newBalance") BigDecimal newBalance);

	@Modifying
	@Query("update UserAccount u set u.balance = :newBalance, u.freezeBalance = :newFreezeBalance where u.userId = :userId")
    void uodateByUserId(@Param("userId") long userId, @Param("newBalance") BigDecimal newBalance, @Param("newFreezeBalance") BigDecimal newFreezeBalance);
}
